package per.kongtouxu.service.Impl;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import per.kongtouxu.dao.UserDao;
import per.kongtouxu.dao.UserScoreIoDao;
import per.kongtouxu.domain.pojo.User;
import per.kongtouxu.domain.pojo.UserScoreIo;
import per.kongtouxu.service.UserService;

import java.io.IOException;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserScoreIoDao userScoreIoDao;
    @Override
    public User loginUser(String account, String password) {
        User user = null;
        try {
            user = userDao.findUserByUP(account, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  user;
    }

    @Override
    public int saveUser(User user) {
        //先查询是否存在用户
        User alreadUser =null;
        int result = 0;
        try {
            //判断用户是否存在
           alreadUser = userDao.findUserByAccount(user.getUserName());
            System.out.println("查询到的结果:"+alreadUser);
            if (alreadUser == null){
                //用户不存在，可以保存
                result= userDao.saveUser(user);
                System.out.println("result:"+result);
                //2.4添加流水
                UserScoreIo ScoreIo = new UserScoreIo();
                ScoreIo.setUserId(user.getUserId());
                ScoreIo.setScore(20);
                ScoreIo.setScoreState("注册");
                userScoreIoDao.add(ScoreIo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            return result;
        }
    }

    @Override
    public User findUserByAccount(String account) {
        //获取代理对象
        User user = userDao.findUserByAccount(account);
        return user;
    }

    @Override
    public User findUserById(Integer userId) {

        return userDao.findUserById(userId);
    }

    @Override
    public void updateScoreByUserId(Integer userId, Integer userScore) {
        userDao.updateScoreByUserId(userId,userScore);
    }
}
